package com.mocaris.android.gank.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import com.mocaris.android.gank.R
import com.mocaris.android.gank.model.SystemTree
import kotlinx.android.synthetic.main.item_system_tree_parent.view.*

class SystreeAdapter(private val context: Context) : BaseExpandableListAdapter() {

    var data = arrayListOf<SystemTree>()
        set(value) {
            field = value
            notifyDataSetChanged()
        }


    override fun getGroup(position: Int): SystemTree {
        return data[position]
    }

    override fun isChildSelectable(parentPosition: Int, childPosition: Int): Boolean {
        return true
    }

    override fun hasStableIds(): Boolean {
        return true
    }

    override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?): View {
        val holder = if (null == convertView) {
            val view = LayoutInflater.from(context).inflate(R.layout.item_system_tree_parent, parent, false)
            val holder = ViewHolder(view)
            view.tag = holder
            holder
        } else convertView.tag as ViewHolder
        val group = getGroup(groupPosition)
        holder.itemView.tv_title.text = group.name
        holder.itemView.img_allow_right.isSelected = isExpanded
        return holder.itemView
    }

    override fun getChildrenCount(position: Int): Int {
        return data[position].children.size
    }

    override fun getChild(groupPosition: Int, childPosition: Int): SystemTree {
        return data[groupPosition].children[childPosition]
    }

    override fun getGroupId(position: Int): Long {
        return data[position].id
    }

    override fun getChildView(
        groupPosition: Int,
        childPosition: Int,
        isLastChild: Boolean,
        convertView: View?,
        parent: ViewGroup?
    ): View {
        val holder = if (null == convertView) {
            val view = LayoutInflater.from(context).inflate(R.layout.item_system_tree_child, parent, false)
            val holder = ViewHolder(view)
            view.tag = holder
            holder
        } else convertView.tag as ViewHolder
        val child = getChild(groupPosition, childPosition)
        holder.itemView.tv_title.text = child.name
        holder.itemView.setBackgroundColor(context.resources.getColor(R.color.txt_color_hint))
        return holder.itemView
    }

    override fun getChildId(groupPosition: Int, childPosition: Int): Long {
        return data[groupPosition].children[childPosition].id
    }

    override fun getGroupCount(): Int {
        return data.size
    }


    class ViewHolder(val itemView: View)


}